package com.yunfinal.api.tpl.template.directive.db;

import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;

/**
 * Db.use().tx(
 * 数据库事务
 * #dbTx()
 * 包裹代码
 * 手动回滚: #set(DbTxResult=false)
 * #end
 * @author  杜福忠
 */
public class DbTxDirective extends Directive {
    private final static String dbTxResult = "DbTxResult";

    @Override
    public void exec(Env env, Scope scope, Writer writer) {
        DbConfigName.db().tx(() -> {
            stat.exec(env, scope, writer);
            Object result = scope.get(dbTxResult);
            if (result != null) {
                if (result instanceof Boolean) {
                    return (Boolean) result;
                }
                if ("false".equals(result.toString())) {
                    return false;
                }
            }
            return true;
        });
    }

    @Override
    public boolean hasEnd() {
        return true;
    }
}
